package com.kkb.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kkb.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 会员
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map<String, String> map){
        try {
            //1. 校验用户输入的短信验证码是否正确
            String telephone = map.get("telephone");
            String validateCode = map.get("validateCode");
            //获取redis中的验证码
            String code4Redis = stringRedisTemplate.boundValueOps("member.validateCode").get();

            System.out.println("telephone=" + telephone +", validateCode="+ validateCode+", code4Redis="+code4Redis);

            //2. 如果验证码错误，则登录失败
            if( !code4Redis.equals(validateCode)){
                return new Result(false, "验证码输入有误, 请重新输入");
            }

            //如果验证码成功，调用service,完成用户登录

            //登录成功, 返回成功信息
            return new Result(true, "登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            //登录失败, 返回失败信息
            return new Result(false, "登录失败");
        }
    }

    /**
     * 环境测试 : 验证码登录
     */
    @GetMapping("/smsLogin")
    public String smsLogin_bak(Map map) throws JsonProcessingException {
        String validateCode = stringRedisTemplate.boundValueOps("member.validateCode").get();

        if (validateCode == null) {
            String code = "hello";

            ObjectMapper jsonFormat = new ObjectMapper();
            validateCode = jsonFormat.writeValueAsString(code);

            stringRedisTemplate.boundValueOps("member.validateCode").set(validateCode);
            System.out.println("=============生成验证码, 阿里云短信通知用户, 存入验证码到Redis===============");
        } else {
            System.out.println("=============从Redis缓存中获取验证码数据===============");
        }

        System.out.println("validateCode = " + validateCode);

        return validateCode;
    }
}
